import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

const DEFAULT_MODULE = {
  namespaced: true,
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {}
};

/**
 * 自动加载文件作为vuex的module
 */
let files = require.context('./modules', true, /\.js$/);
const modules = {};
const keys = files.keys().filter((item) => !item.endsWith('.local.js'));

keys.forEach((key) => {
  // 将文件路径转换成对象
  const processKey = key.replace(/(\.\/|\.js)/g, '');
  let keyToPath = processKey.split('/');
  let module = keyToPath[0];
  const indexPath = `./${module}/index.js`;
  // 暂时只支持 下级目录
  if (!modules[module]) {
    // 先判断是否存在 index.js
    if (keys.indexOf(indexPath) > -1) {
      modules[module] = {
        ...DEFAULT_MODULE,
        ...files(indexPath).default
      };
    } else {
      modules[module] = {
        ...DEFAULT_MODULE
      };
    }
  }
  if (key !== indexPath) {
    modules[module].modules[keyToPath[1]] = {
      namespaced: true,
      ...files(key).default
    };
  }
});
export default new Vuex.Store({
  modules: {
    ...modules
  }
  // strict: debug
  // plugins: debug ? [createLogger()] : []
});
